package com.ztom.top100;

import java.util.HashMap;
import java.util.Map;

/**
 * 从前序与中序遍历序列构造二叉树
 * <p>
 * https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
 *
 * @author ZhangTao
 */
public class Code43BuildTree {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder == null || preorder.length == 0
                || inorder == null || inorder.length == 0
                || preorder.length != inorder.length) {
            return null;
        }

        // 记录节点在中序中的 index
        Map<Integer, Integer> indexMap = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) {
            indexMap.put(inorder[i], i);
        }

        return buildTree(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1, indexMap);
    }

    private TreeNode buildTree(int[] preorder, int l1, int r1, int[] inorder, int l2, int r2, Map<Integer, Integer> indexMap) {
        if (l1 > r1 || l2 > r2) {
            return null;
        }
        // 先序第一个节点就是根节点
        TreeNode root = new TreeNode(preorder[l1]);
        // 找到中序中根节点的位置, 则左边是左子树, 右边是右子树
        Integer rootInOrderIndex = indexMap.get(preorder[l1]);
        // 左子树节点数
        int leftCount = rootInOrderIndex - l2;

        root.left = buildTree(preorder, l1 + 1, l1 + leftCount, inorder, l2, rootInOrderIndex - 1, indexMap);
        root.right = buildTree(preorder, l1 + leftCount + 1, r1, inorder, rootInOrderIndex + 1, r2, indexMap);

        return root;
    }
}
